﻿using System.Management.Automation;

namespace PSSymbolStore.Commands
{
    public abstract class TransactionCommandBase : SymbolStoreCommandBase
    {
        [Parameter(Position = 1,
            Mandatory = true,
            ParameterSetName = "IndividualTransactions",
            ValueFromPipeline = true,
            ValueFromPipelineByPropertyName = true,
            ValueFromRemainingArguments = true,
            HelpMessage = "The transaction id")]
        public string[] TransactionId { get; set; }

        protected virtual string ActivityName
        {
            get
            {
                return "Process Transaction";
            }
        }

        protected virtual void ProcessTransaction(string transactionId)
        {
            // No-op
        }

        private ProgressRecord _progressRecord = null;

        protected override void BeginProcessing()
        {
            _progressRecord = new ProgressRecord(0, ActivityName, "Processing transactions");

            base.BeginProcessing();
        }

        protected override void ProcessRecord()
        {
            if ((TransactionId != null) && (TransactionId.Length > 0))
            {
                int i = 0;
                int len = TransactionId.Length;
                _progressRecord.RecordType = ProgressRecordType.Processing;
                foreach (string id in TransactionId)
                {
                    ProcessTransaction(id);
                    _progressRecord.PercentComplete = (int) (((double)i/(double)len) * 100);
                    WriteProgress(_progressRecord);
                    i++;
                }
            }

            base.ProcessRecord();
        }

        protected override void EndProcessing()
        {
            _progressRecord.RecordType = ProgressRecordType.Completed;
            _progressRecord.PercentComplete = 100;
            WriteProgress(_progressRecord);

            base.EndProcessing();
        }
    }
}
